<?php


namespace App\Service;


use Swoole\WebSocket\Server;

class ChatService
{
    /**
     * 房间发送信息
     * @param string $msg
     * @param $room_id
     * @param \Swoole\Http\Response|Server $server
     * @param $for {发送人uid}
     * @param string $cmd
     */
    public static function msgToRoom(string $msg, $room_id, $server, $for, $cmd = 'chat')
    {
        if (!$server) {
            $server = websocket();
        }
        $users = RoomService::getRoomUser($room_id);
        foreach ($users as $user) {
            self::msg($msg, $user['fd'], $server, $for, 2, $cmd);
        }
    }


    /**
     * 消息通知
     * @param string $msg
     * @param $fd
     * @param $server
     * @param int $for {发送人uid}
     * @param int $type 1私聊 2房间 3世界 4公告
     * @param string $cmd
     * @return mixed
     */
    public static function msg(string $msg, $fd, $server, $for = 0,  $type = 1, $cmd = 'chat')
    {
        return $server->push((int)$fd, json_encode(['code' => 200, 'data' => ['msg' => $msg, 'cmd' => $cmd, 'type' => $type, 'for' => $for]]));
    }
}